

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/egg.png">
  <link rel="icon" href="/img/egg.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="十一的蛋炒饭">
  <meta name="keywords" content="">
  
    <meta name="description" content="请求响应：  请求（HttpServletRequest）：获取请求数据 响应（HttpServletResponse）：设置响应数据 BS 架构：Browser &#x2F; Server ,浏览器 &#x2F; 服务器架构模式。客户端只需要浏览器，应用程序的逻辑和数据都存储在服务器（维护方便，体验一般）。 CS架构：Client &#x2F; Server，客户端 &#x2F; 服务器架构模式">
<meta property="og:type" content="article">
<meta property="og:title" content="Web 开发笔记3 | Postman 、SpringBoot 获取不同的请求参数、Spring Boot 响应数据、Spring 的 IOC控制反转和DI 依赖注入、项目分层解耦的实现、Bean 注入的注解">
<meta property="og:url" content="http://example.com/2024/03/12/Web-%E5%BC%80%E5%8F%91%E7%AC%94%E8%AE%B03-Postman-%E3%80%81SpringBoot-%E8%8E%B7%E5%8F%96%E4%B8%8D%E5%90%8C%E7%9A%84%E8%AF%B7%E6%B1%82%E5%8F%82%E6%95%B0%E3%80%81Spring-Boot-%E5%93%8D%E5%BA%94%E6%95%B0%E6%8D%AE%E3%80%81Spring-%E7%9A%84-IOC%E6%8E%A7%E5%88%B6%E5%8F%8D%E8%BD%AC%E5%92%8CDI-%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85%A5%E3%80%81%E9%A1%B9%E7%9B%AE%E5%88%86%E5%B1%82%E8%A7%A3%E8%80%A6%E7%9A%84%E5%AE%9E%E7%8E%B0%E3%80%81Bean-%E6%B3%A8%E5%85%A5%E7%9A%84%E6%B3%A8%E8%A7%A3/index.html">
<meta property="og:site_name" content="十一的蛋炒饭的博客">
<meta property="og:description" content="请求响应：  请求（HttpServletRequest）：获取请求数据 响应（HttpServletResponse）：设置响应数据 BS 架构：Browser &#x2F; Server ,浏览器 &#x2F; 服务器架构模式。客户端只需要浏览器，应用程序的逻辑和数据都存储在服务器（维护方便，体验一般）。 CS架构：Client &#x2F; Server，客户端 &#x2F; 服务器架构模式">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403111941744.png">
<meta property="og:image" content="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403111936676.png">
<meta property="og:image" content="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403112039712.png">
<meta property="og:image" content="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403112046817.png">
<meta property="og:image" content="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403112251163.png">
<meta property="og:image" content="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403120441339.png">
<meta property="og:image" content="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403120506078.png">
<meta property="article:published_time" content="2024-03-12T04:00:00.000Z">
<meta property="article:modified_time" content="2024-03-13T04:11:27.060Z">
<meta property="article:author" content="十一的蛋炒饭">
<meta property="article:tag" content="SpringBoot">
<meta property="article:tag" content="Postman">
<meta property="article:tag" content="Spring">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403111941744.png">
  
  
  
  <title>Web 开发笔记3 | Postman 、SpringBoot 获取不同的请求参数、Spring Boot 响应数据、Spring 的 IOC控制反转和DI 依赖注入、项目分层解耦的实现、Bean 注入的注解 - 十一的蛋炒饭的博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.7","typing":{"enable":true,"typeSpeed":60,"cursorChar":"","loop":false,"scope":["home"]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":"§"},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 7.1.1"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>十一的蛋炒饭 的博客</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/" target="_self">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/" target="_self">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/" target="_self">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/" target="_self">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/" target="_self">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/win7.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle">Web 开发笔记3 | Postman 、SpringBoot 获取不同的请求参数、Spring Boot 响应数据、Spring 的 IOC控制反转和DI 依赖注入、项目分层解耦的实现、Bean 注入的注解</span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2024-03-12 12:00" pubdate>
          2024年3月12日 中午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          2.3k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          19 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar category-bar" style="margin-right: -1rem">
    





<div class="category-list">
  
  
    
    
    
    <div class="category row nomargin-x">
      <a class="category-item 
          list-group-item category-item-action col-10 col-md-11 col-xm-11" title="Web开发"
        id="heading-3b451acfb78b69289662a6dd4d9d042c" role="tab" data-toggle="collapse" href="#collapse-3b451acfb78b69289662a6dd4d9d042c"
        aria-expanded="true"
      >
        Web开发
        <span class="list-group-count">(3)</span>
        <i class="iconfont icon-arrowright"></i>
      </a>
      
      <div class="category-collapse collapse show" id="collapse-3b451acfb78b69289662a6dd4d9d042c"
           role="tabpanel" aria-labelledby="heading-3b451acfb78b69289662a6dd4d9d042c">
        
        
          
  <div class="category-post-list">
    
    
      
      
        <a href="/2024/03/06/Web-%E5%BC%80%E5%8F%91%E7%AC%94%E8%AE%B01-%E5%89%8D%E5%90%8E%E7%AB%AF%E5%88%86%E7%A6%BB%E5%BC%80%E5%8F%91%E3%80%81Vue2%E9%A1%B9%E7%9B%AE%E5%BC%80%E5%8F%91/" title="Web 开发笔记1 | 前后端分离开发、Vue2项目开发"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">Web 开发笔记1 | 前后端分离开发、Vue2项目开发</span>
        </a>
      
    
      
      
        <a href="/2024/03/11/Web%E5%BC%80%E5%8F%91%E7%AC%94%E8%AE%B02-%E5%90%8E%E7%AB%AF-Spring-Boot%E3%80%81HTTP%E5%8D%8F%E8%AE%AE%E3%80%81Web%E6%9C%8D%E5%8A%A1%E5%99%A8%E3%80%81Tomcat/" title="Web 开发笔记2 | 后端 Spring Boot、HTTP协议、Web服务器、Tomcat"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">Web 开发笔记2 | 后端 Spring Boot、HTTP协议、Web服务器、Tomcat</span>
        </a>
      
    
      
      
        <a href="/2024/03/12/Web-%E5%BC%80%E5%8F%91%E7%AC%94%E8%AE%B03-Postman-%E3%80%81SpringBoot-%E8%8E%B7%E5%8F%96%E4%B8%8D%E5%90%8C%E7%9A%84%E8%AF%B7%E6%B1%82%E5%8F%82%E6%95%B0%E3%80%81Spring-Boot-%E5%93%8D%E5%BA%94%E6%95%B0%E6%8D%AE%E3%80%81Spring-%E7%9A%84-IOC%E6%8E%A7%E5%88%B6%E5%8F%8D%E8%BD%AC%E5%92%8CDI-%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85%A5%E3%80%81%E9%A1%B9%E7%9B%AE%E5%88%86%E5%B1%82%E8%A7%A3%E8%80%A6%E7%9A%84%E5%AE%9E%E7%8E%B0%E3%80%81Bean-%E6%B3%A8%E5%85%A5%E7%9A%84%E6%B3%A8%E8%A7%A3/" title="Web 开发笔记3 | Postman 、SpringBoot 获取不同的请求参数、Spring Boot 响应数据、Spring 的 IOC控制反转和DI 依赖注入、项目分层解耦的实现、Bean 注入的注解"
           class="list-group-item list-group-item-action
           active">
          <span class="category-post">Web 开发笔记3 | Postman 、SpringBoot 获取不同的请求参数、Spring Boot 响应数据、Spring 的 IOC控制反转和DI 依赖注入、项目分层解耦的实现、Bean 注入的注解</span>
        </a>
      
    
  </div>

        
      </div>
    </div>
  
</div>


  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">Web 开发笔记3 | Postman 、SpringBoot 获取不同的请求参数、Spring Boot 响应数据、Spring 的 IOC控制反转和DI 依赖注入、项目分层解耦的实现、Bean 注入的注解</h1>
            
              <p id="updated-time" class="note note-info" style="display: none">
                
                  
                    本文最后更新于 2024-03-13T12:11:27+08:00
                  
                  

                
              </p>
            
            
              <div class="markdown-body">
                
                <p>请求响应：</p>
<ul>
<li>请求（HttpServletRequest）：获取请求数据</li>
<li>响应（HttpServletResponse）：设置响应数据</li>
<li>BS 架构：Browser &#x2F; Server ,浏览器 &#x2F; 服务器架构模式。客户端只需要浏览器，应用程序的逻辑和数据都存储在服务器（维护方便，体验一般）。</li>
<li>CS架构：Client &#x2F; Server，客户端 &#x2F; 服务器架构模式。（开发、维护麻烦，体验不错）。</li>
</ul>
<h2 id="1、Postman"><a href="#1、Postman" class="headerlink" title="1、Postman"></a>1、Postman</h2><p><code>Postman</code> 是一款 功能强大的网页调试与发送网页 HTTP 请求的 Chrome 插件，其作用是常用于进行接口测试。</p>
<p>Postman 官网：<strong><a target="_blank" rel="noopener" href="https://www.postman.com/">https://www.postman.com/</a></strong> </p>
<p>使用 Postman 前需要注册账号，推荐下载其客户端进行操作，比较方便，我们可以用 Postman 向后端发送请求。</p>
<h2 id="2、SpringBoot-获取请求参数"><a href="#2、SpringBoot-获取请求参数" class="headerlink" title="2、SpringBoot 获取请求参数"></a>2、SpringBoot 获取请求参数</h2><h3 id="2-1-简单参数"><a href="#2-1-简单参数" class="headerlink" title="2.1 简单参数"></a>2.1 简单参数</h3><p><strong>原始方式：</strong>在原始的 web 程序中，获取请求参数，需要通过 HttpServletRequest 对象手动获取。</p>
<p><strong>案例：测试 SpringBoot 的原始方式获取参数，用 Postman 发送 GET 请求。</strong></p>
<p><strong>后端接口：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> cn.ccuni.controller;<br><br><span class="hljs-keyword">import</span> jakarta.servlet.http.HttpServletRequest;<br><span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.RequestMapping;<br><span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.RestController;<br><br><span class="hljs-comment">// 请求处理类</span><br><span class="hljs-meta">@RestController</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">HelloController</span> &#123;<br>    <span class="hljs-meta">@RequestMapping(&quot;/simpleParam&quot;)</span><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">simpleParam</span><span class="hljs-params">(HttpServletRequest request)</span>&#123;<br>        <span class="hljs-comment">// 获取请求参数</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">name</span> <span class="hljs-operator">=</span> request.getParameter(<span class="hljs-string">&quot;name&quot;</span>);<br>        <span class="hljs-type">String</span> <span class="hljs-variable">ageStr</span> <span class="hljs-operator">=</span> request.getParameter(<span class="hljs-string">&quot;age&quot;</span>);<br>        <span class="hljs-type">int</span> <span class="hljs-variable">age</span> <span class="hljs-operator">=</span> Integer.parseInt(ageStr);<br>        System.out.println(name + <span class="hljs-string">&quot;: &quot;</span> + age);<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;OK&quot;</span>;<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p><strong>Postman：</strong></p>
<p><img src="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403111941744.png" srcset="/img/loading.gif" lazyload alt="image-20240311194106686"></p>
<p><strong>测试结果：</strong></p>
<p><img src="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403111936676.png" srcset="/img/loading.gif" lazyload alt="image-20240311193644415"></p>
<p>Spring Boot 处理 GET 请求时接收的参数可以简写，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(value = &quot;/simpleParam&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">simpleParam</span><span class="hljs-params">(String name, Integer age)</span>&#123;<br>    <span class="hljs-comment">// 获取请求参数</span><br>    System.out.println(name + <span class="hljs-string">&quot;: &quot;</span> + age);<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;OK&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>



<p>除了上面这种方式外，还可以通过给参数添加 <code>@RequestParam</code> 注解来限制参数。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@PostMapping(value = &quot;/simpleParam&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">simpleParam</span><span class="hljs-params">(<span class="hljs-meta">@RequestParam(required = true)</span> String name,</span><br><span class="hljs-params">                          <span class="hljs-meta">@RequestParam(required = false)</span> Integer age)</span>&#123;<br>    <span class="hljs-comment">// 获取请求参数</span><br>    System.out.println(name + <span class="hljs-string">&quot;: &quot;</span> + age);<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;OK&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>



<p>总结如下：</p>
<ol>
<li><strong>原始方法获取请求参数</strong></li>
</ol>
<ul>
<li>Controller 方法形参中声明 HttpServletRequest 对象。</li>
<li>调用对象的 getParameter(参数名)。</li>
</ul>
<ol start="2">
<li><strong>Spring Boot 中接收简单参数</strong></li>
</ol>
<ul>
<li>请求参数名与方法形参变量名相同。</li>
<li>会自动进行类型转换。</li>
</ul>
<ol start="3">
<li><strong>@RequestParam 注解</strong></li>
</ol>
<ul>
<li>方法形参名称与请求参数名称若不一致，则通过该注释完成映射。</li>
<li>该注解的 required 属性默认是 true，代表请求参数必须传递。</li>
</ul>
<h3 id="2-2-实体参数"><a href="#2-2-实体参数" class="headerlink" title="2.2 实体参数"></a>2.2 实体参数</h3><p><strong>简单实体对象：</strong>请求参数名与形参对象属性名相同，定义 POJO 接收即可。</p>
<p><code>User.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> cn.ccuni.pojo;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">User</span> &#123;<br>    <span class="hljs-keyword">private</span> String name;<br>    <span class="hljs-keyword">private</span> Integer age;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setName</span><span class="hljs-params">(String name)</span> &#123;<br>        <span class="hljs-built_in">this</span>.name = name;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setAge</span><span class="hljs-params">(Integer age)</span> &#123;<br>        <span class="hljs-built_in">this</span>.age = age;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">toString</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;User&#123;&quot;</span> +<br>                <span class="hljs-string">&quot;name=&#x27;&quot;</span> + name + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> +<br>                <span class="hljs-string">&quot;, age=&quot;</span> + age +<br>                <span class="hljs-string">&#x27;&#125;&#x27;</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><code>Controller.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(&quot;/simplePojo&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">simplePojo</span><span class="hljs-params">(User user)</span>&#123;<br>    System.out.println(user);<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;OK&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>Postman</p>
<p><img src="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403112039712.png" srcset="/img/loading.gif" lazyload alt="image-20240311203928624"></p>
<p><strong>复杂实体对象：</strong>请求参数名与形参对象属性名相同，按照对象层次结构关系即可接收嵌套 POJO 属性参数。</p>
<p>如在上面的 User对象中加入一个Location对象表示位置，接下来都省略Setter方法、Getter方法和 toString方法。</p>
<p><code>User.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">User</span> &#123;<br>    <span class="hljs-keyword">private</span> String name;<br>    <span class="hljs-keyword">private</span> Integer age;<br>    <span class="hljs-keyword">private</span> Location location;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><code>Location.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Location</span> &#123;<br>    <span class="hljs-keyword">private</span> String province;<br>    <span class="hljs-keyword">private</span> String city;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>Postman</p>
<p><img src="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403112046817.png" srcset="/img/loading.gif" lazyload alt="image-20240311204646732"></p>
<h3 id="2-3-数组集合参数"><a href="#2-3-数组集合参数" class="headerlink" title="2.3 数组集合参数"></a>2.3 数组集合参数</h3><p><strong>数组参数：</strong>请求参数名与形参数组名称相同且请求参数为多个，定义数组类型形参即可接收参数。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(&quot;/arrayParam&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">arrayParam</span><span class="hljs-params">(String[] hobby)</span>&#123;<br>    <span class="hljs-keyword">if</span>(hobby != <span class="hljs-literal">null</span>)<br>        <span class="hljs-keyword">for</span> (String s : hobby) &#123;<br>            System.out.println(s);<br>        &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;OK&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403112251163.png" srcset="/img/loading.gif" lazyload alt="image-20240311225140061"></p>
<p><strong>集合参数：</strong> 请求参数名与形参名称相同且请求参数为多个，用<code>@RequestParam</code>绑定参数关系。（Postman和上图配置一样。）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(&quot;/listParam&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">listParam</span><span class="hljs-params">(<span class="hljs-meta">@RequestParam</span> List&lt;String&gt; hobby)</span>&#123;<br>    System.out.println(hobby);<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;OK&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="2-4-日期参数"><a href="#2-4-日期参数" class="headerlink" title="2.4 日期参数"></a>2.4 日期参数</h3><p>日期参数：使用 <code>@DateTimeFormat</code> 注解完成日期参数格式转换。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(&quot;/dateParam&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">dateParam</span><span class="hljs-params">(</span><br><span class="hljs-params">    <span class="hljs-meta">@DateTimeFormat(pattern = &quot;yyyy-MM-dd HH:mm:ss&quot;)</span>String updateTime)</span>&#123;<br>    System.out.println(<span class="hljs-string">&quot;更新时间: &quot;</span> + updateTime);<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;OK&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>postman发送请求</p>
<p><img src="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403120441339.png" srcset="/img/loading.gif" lazyload alt="image-20240312044112192"></p>
<p>输出结果：2024-3-12 04:37:36</p>
<h3 id="2-5-JSON参数"><a href="#2-5-JSON参数" class="headerlink" title="2.5 JSON参数"></a>2.5 JSON参数</h3><p><strong>JSON 参数：</strong>JSON 数据键名与形参对象属性名相同，定义 POJO 类型形象即可接收参数，需要使用 @RequestBody 标识，通常是处理POST请求里的请求体带的JSON数据。</p>
<p>接口 <code>Controller.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@PostMapping(&quot;/jsonParam&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">jsonParam</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> User user)</span>&#123;<br>    System.out.println(user);<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;OK&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>请求的 JSON 数据：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><br>    <span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;uni&quot;</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-number">23</span><span class="hljs-punctuation">,</span><br>    <span class="hljs-attr">&quot;location&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span><br>        <span class="hljs-attr">&quot;province&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;浙江省&quot;</span><span class="hljs-punctuation">,</span><br>        <span class="hljs-attr">&quot;city&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;温州市&quot;</span><br>    <span class="hljs-punctuation">&#125;</span><br><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h3 id="2-6-路径参数"><a href="#2-6-路径参数" class="headerlink" title="2.6 路径参数"></a>2.6 路径参数</h3><p>路径参数：通过请求 URL 直接传递参数，使用<code>&#123;...&#125;</code>来标识该路径参数，需要使用 <code>@PathVariable</code> 获取路径参数。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(&quot;/path/&#123;id&#125;/&#123;name&#125;&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">pathParam</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable</span> Integer id,</span><br><span class="hljs-params">                        <span class="hljs-meta">@PathVariable</span> String name)</span>&#123;<br>    System.out.println(<span class="hljs-string">&quot;ID:&quot;</span> + id + <span class="hljs-string">&quot;, NAME: &quot;</span> +name);<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;OK&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>postman 请求路径</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bash">http://localhost:8080/path/1/uni<br></code></pre></td></tr></table></figure>

<h2 id="3、SpringBoot-响应数据"><a href="#3、SpringBoot-响应数据" class="headerlink" title="3、SpringBoot 响应数据"></a>3、SpringBoot 响应数据</h2><h3 id="3-1-ResponseBody"><a href="#3-1-ResponseBody" class="headerlink" title="3.1 @ResponseBody"></a>3.1 @ResponseBody</h3><p><strong>注解：@ResponseBody</strong></p>
<p><strong>类型：</strong>方法注解、类注解</p>
<p><strong>位置：</strong>Controller 方法 &#x2F; 接口类上</p>
<p><strong>作用：</strong>将方法返回值直接响应，若返回值类型是 <code>实体对象或集合</code> ，则会转换为 JSON 格式响应</p>
<p><code>注：@RestController  = @Controller + @RequestBody</code></p>
<p><img src="https://uni-pic-bed.oss-cn-hangzhou.aliyuncs.com/blog2024/202403120506078.png" srcset="/img/loading.gif" lazyload alt="image-20240312050637819"></p>
<h3 id="3-2-统一响应数据的格式"><a href="#3-2-统一响应数据的格式" class="headerlink" title="3.2 统一响应数据的格式"></a>3.2 统一响应数据的格式</h3><p>由于不同的请求，可能会响应不同的数据格式，为方便开发人员接收响应，需要统一数据格式，比如每个请求都返回同一个封装后的类，<code>Result.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> cn.ccuni.pojo;<br><span class="hljs-comment">// 统一响应数据的格式</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Result</span> &lt;T&gt; &#123;<br>    <span class="hljs-keyword">private</span> Integer code;<br>    <span class="hljs-keyword">private</span> String msg;<br>    <span class="hljs-keyword">private</span> T data;<br>    <span class="hljs-comment">// 无参构造方法</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">Result</span><span class="hljs-params">()</span>&#123;&#125;<br>    <span class="hljs-comment">// 全参构造</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">Result</span><span class="hljs-params">(Integer code, String msg, T data)</span>&#123;<br>        <span class="hljs-built_in">this</span>.code = code;<br>        <span class="hljs-built_in">this</span>.msg = msg;<br>        <span class="hljs-built_in">this</span>.data = data;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> Integer <span class="hljs-title function_">getCode</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> code;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setCode</span><span class="hljs-params">(Integer code)</span> &#123;<br>        <span class="hljs-built_in">this</span>.code = code;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">getMsg</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> msg;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setMsg</span><span class="hljs-params">(String msg)</span> &#123;<br>        <span class="hljs-built_in">this</span>.msg = msg;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> T <span class="hljs-title function_">getData</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> data;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setData</span><span class="hljs-params">(T data)</span> &#123;<br>        <span class="hljs-built_in">this</span>.data = data;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> &lt;T&gt;Result <span class="hljs-title function_">success</span><span class="hljs-params">(T data)</span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Result</span>(<span class="hljs-number">1</span>, <span class="hljs-string">&quot;success&quot;</span>, data);<br>    &#125;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Result <span class="hljs-title function_">success</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Result</span>(<span class="hljs-number">1</span>, <span class="hljs-string">&quot;success&quot;</span>, <span class="hljs-literal">null</span>);<br>    &#125;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Result <span class="hljs-title function_">error</span><span class="hljs-params">(String msg)</span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Result</span>(<span class="hljs-number">0</span>, msg, <span class="hljs-literal">null</span>);<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">toString</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Result&#123;&quot;</span> +<br>                <span class="hljs-string">&quot;code=&quot;</span> + code +<br>                <span class="hljs-string">&quot;, msg=&#x27;&quot;</span> + msg + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> +<br>                <span class="hljs-string">&quot;, data=&quot;</span> + data +<br>                <span class="hljs-string">&#x27;&#125;&#x27;</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p>测试接口：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(&quot;/hello&quot;)</span><br><span class="hljs-keyword">public</span> Result&lt;String&gt; <span class="hljs-title function_">hello</span><span class="hljs-params">()</span>&#123;<br>    System.out.println(<span class="hljs-string">&quot;Hello,World!&quot;</span>);<br>    <span class="hljs-keyword">return</span> Result.success(<span class="hljs-string">&quot;Hello, World!&quot;</span>);<br>&#125;<br><span class="hljs-meta">@GetMapping(&quot;/getUser/&#123;name&#125;&quot;)</span><br><span class="hljs-keyword">public</span> Result&lt;User&gt; <span class="hljs-title function_">getUser</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable</span> String name)</span>&#123;<br>    <span class="hljs-type">User</span> <span class="hljs-variable">user</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">User</span>();<br>    user.setName(name);<br>    user.setAge(<span class="hljs-number">23</span>);<br>    <span class="hljs-keyword">return</span> Result.success(user.toString());<br>&#125;<br></code></pre></td></tr></table></figure>



<p>统一响应的数据格式后，代码可读性更高。</p>
<h2 id="4、项目分层解耦"><a href="#4、项目分层解耦" class="headerlink" title="4、项目分层解耦"></a>4、项目分层解耦</h2><h3 id="4-1-三层架构"><a href="#4-1-三层架构" class="headerlink" title="4.1 三层架构"></a>4.1 三层架构</h3><p>后端开发通常分为三层，依次是：Controller、Service、DAO</p>
<ul>
<li><strong>Controller：</strong>控制层，接收前端发送的请求，对请求进行处理，并响应数据。</li>
<li><strong>Service：</strong>业务逻辑层，处理具体的业务逻辑。</li>
<li><strong>DAO：</strong>数据访问层（Data Access Object）（持久层），负责数据访问操作，包括数据的增、删、改、查。</li>
</ul>
<h3 id="4-2-分层解耦-Spring-特性"><a href="#4-2-分层解耦-Spring-特性" class="headerlink" title="4.2 分层解耦 [Spring 特性]"></a>4.2 分层解耦 [Spring 特性]</h3><p><strong>内聚：</strong> 软件中各个功能模块内部的功能联系。</p>
<p><strong>耦合：</strong> 衡量软件中各个层 &#x2F; 模块之间的依赖、关联的程度。</p>
<p><strong>软件设计原则：</strong>高内聚，低耦合。</p>
<p><strong>Spring 特性：</strong></p>
<ul>
<li><strong>控制反转：</strong>Inversion Of Control，简称IOC。对象的创建控制权由程序自身转移到外部（容器）。</li>
<li><strong>依赖注入：</strong>Dependency Injection，简称 DI。容器为应用程序提供运行时，所依赖的资源，称之为依赖注入。</li>
<li><strong>Bean 对象：</strong>IOC容器中创建、管理的对象，称之为bean。</li>
</ul>
<h3 id="4-3-IOC-DI-入门"><a href="#4-3-IOC-DI-入门" class="headerlink" title="4.3 IOC &amp; DI 入门"></a>4.3 IOC &amp; DI 入门</h3><p>一共有3个步骤：</p>
<ol>
<li>Service 层及 DAO层的实现类，交给 IOC 容器管理，即控制反转，对类使用<code>@Component</code>注解。</li>
<li>为 Controller 及 Service 注入运行时依赖的对象，即依赖注入，使用 <code>@Autowired</code> 注解。</li>
<li><strong>运行测试。</strong></li>
</ol>
<h3 id="4-4-Bean-的声明"><a href="#4-4-Bean-的声明" class="headerlink" title="4.4 Bean 的声明"></a>4.4 Bean 的声明</h3><p>在实现控制反转时，要把某个对象交给 IOC 容器管理，需要在对应的类上加入相应的注解，相关注解有：</p>
<table>
<thead>
<tr>
<th>注解</th>
<th>说明</th>
<th>位置</th>
</tr>
</thead>
<tbody><tr>
<td>@Component</td>
<td>声明bean的基础注解</td>
<td>不属于以下三类时，使用此注解</td>
</tr>
<tr>
<td>@Controller</td>
<td>@Component的衍生注解</td>
<td>标注在控制器的类上</td>
</tr>
<tr>
<td>@Service</td>
<td>@Component的衍生注解</td>
<td>标注在业务类上</td>
</tr>
<tr>
<td>@Repository</td>
<td>@Component的衍生注解</td>
<td>标注在数据访问类上（由于和 MyBatis 整合，所以用的少）</td>
</tr>
</tbody></table>
<p>在使用IOC和DI前，需要设置组件扫描，通过注解 <code>@ComponentScan</code> 实现。</p>
<p>该注解目前已在 Spring Boot 启动类上的 <code>@SpringBootApplication</code>中包含，默认扫描的范围是启动类所在包及其子包。</p>
<h3 id="4-5-Bean-的注入"><a href="#4-5-Bean-的注入" class="headerlink" title="4.5 Bean 的注入"></a>4.5 Bean 的注入</h3><p>之前实现依赖注入的注解是 <code>@Autowired</code>，该注解默认是按照类型进行，若存在多个相同类型的 bean ，则会发生报错。</p>
<p>解决办法：使用其他的注解，有：<code>@Primary</code>、<code>@Qualifier</code>、<code>@Resource</code></p>
<h4 id="Primary"><a href="#Primary" class="headerlink" title="@Primary"></a>@Primary</h4><p><code>@Primary</code>的作用是标注在其他的类上方，这样 <code>@Autowired</code>在遇到相同类型的 Bean 时，会选择带 <code>@Primary</code>注解的唯一的Bean。</p>
<p>如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Primary</span><br><span class="hljs-meta">@Service</span><br>publci <span class="hljs-keyword">class</span> <span class="hljs-title class_">UserServiceImpl</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">UserService</span>&#123;<br>    <br>&#125;<br></code></pre></td></tr></table></figure>



<h4 id="Qualifier"><a href="#Qualifier" class="headerlink" title="@Qualifier"></a>@Qualifier</h4><p>注解 <code>@Qualifier</code> 也是注入 Bean的注解，不过主要是以名称的方式注入 Bean，例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Autowired</span><br><span class="hljs-keyword">private</span> UserService userSerivce;<br></code></pre></td></tr></table></figure>

<p>相当于</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Qualifier(&quot;userService&quot;)</span><br><span class="hljs-keyword">private</span> UserService userSerivce;<br></code></pre></td></tr></table></figure>



<h4 id="Resource"><a href="#Resource" class="headerlink" title="@Resource"></a>@Resource</h4><p>之前依赖注入相关的注解 <code>@Autowired</code> 、<code>@Primary</code>、<code>@Qualifier</code> 都是 Spring 框架提供的，而 <code>@Resource</code>是 JDK提供的注解。</p>
<p>和 <code>@Qualifier</code> 用法类似：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Qualifier(&quot;userService&quot;)</span><br><span class="hljs-keyword">private</span> UserService userSerivce;<br></code></pre></td></tr></table></figure>

<p>相当于</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Resource(&quot;userService&quot;)</span><br><span class="hljs-keyword">private</span> UserService userSerivce;<br></code></pre></td></tr></table></figure>

<h4 id="Resource-与-Autowired-的区别"><a href="#Resource-与-Autowired-的区别" class="headerlink" title="@Resource 与 @Autowired 的区别"></a>@Resource 与 @Autowired 的区别</h4><p><code>@Autowired</code> 是 Spring 框架提供的注解，而 <code>@Resource</code> 是 JDK 提供的注解。</p>
<p><code>@Autowired</code> 默认是按照类型注入，而 <code>@Resource</code> 默认是按名称注入。</p>
<h4 id="依赖注入的注解-总结"><a href="#依赖注入的注解-总结" class="headerlink" title="依赖注入的注解 总结"></a>依赖注入的注解 总结</h4><p>依赖注入的注解</p>
<ul>
<li><code>@Autowired</code> ：默认按照类型自动匹配。</li>
<li>如果同类型的 Bean 存在多个：<ul>
<li><code>@Primary</code></li>
<li><code>@Autowired</code> + <code>@Qualifier(&quot;bean的名称&quot;)</code></li>
<li><code>@Resource(name=&quot;bean的名称&quot;)</code></li>
</ul>
</li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/Web%E5%BC%80%E5%8F%91/" class="category-chain-item">Web开发</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/SpringBoot/" class="print-no-link">#SpringBoot</a>
      
        <a href="/tags/Postman/" class="print-no-link">#Postman</a>
      
        <a href="/tags/Spring/" class="print-no-link">#Spring</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Web 开发笔记3 | Postman 、SpringBoot 获取不同的请求参数、Spring Boot 响应数据、Spring 的 IOC控制反转和DI 依赖注入、项目分层解耦的实现、Bean 注入的注解</div>
      <div>http://example.com/2024/03/12/Web-开发笔记3-Postman-、SpringBoot-获取不同的请求参数、Spring-Boot-响应数据、Spring-的-IOC控制反转和DI-依赖注入、项目分层解耦的实现、Bean-注入的注解/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>十一的蛋炒饭</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2024年3月12日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2024/03/13/MySQL-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B01-%E6%95%B0%E6%8D%AE%E5%BA%93%E3%80%81%E7%BA%A6%E6%9D%9F%E3%80%81%E5%B8%B8%E8%A7%81%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E3%80%81DDL%E3%80%81DML%E3%80%81DQL%E3%80%81MySQL%E5%A4%9A%E8%A1%A8%E8%AE%BE%E8%AE%A1%E3%80%81%E5%A4%9A%E8%A1%A8%E6%9F%A5%E8%AF%A2%E3%80%81MySQL%E4%BA%8B%E5%8A%A1%E3%80%81%E7%B4%A2%E5%BC%95/" title="MySQL 学习笔记1 | 数据库、约束、常见数据类型、DDL、DML、DQL、MySQL多表设计、多表查询、MySQL事务、索引">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">MySQL 学习笔记1 | 数据库、约束、常见数据类型、DDL、DML、DQL、MySQL多表设计、多表查询、MySQL事务、索引</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2024/03/11/BUG%E8%AE%B0%E5%BD%9513-SpringBoot-%E7%BC%96%E5%86%99%E6%8E%A5%E5%8F%A3%E6%97%B6%E6%8E%A5%E6%94%B6%E4%B8%8D%E5%88%B0%E5%A4%8D%E6%9D%82%E7%9A%84%E5%8F%82%E6%95%B0%E7%B1%BB%E5%9E%8B/" title="BUG记录13 | SpringBoot 编写接口时接收不到复杂的参数类型">
                        <span class="hidden-mobile">BUG记录13 | SpringBoot 编写接口时接收不到复杂的参数类型</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>博客网站基于Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>主题Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>





  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  var relativeDate = function() {
    var updatedTime = document.getElementById('updated-time');
    if (updatedTime) {
      var text = updatedTime.textContent;
      var reg = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})/;
      var matchs = text.match(reg);
      if (matchs) {
        var relativeTime = moment(matchs[0]).fromNow();
        updatedTime.textContent = text.replace(reg, relativeTime);
      }
      updatedTime.style.display = '';
    }
  };
  Fluid.utils.createScript('https://lib.baomitu.com/moment.js/2.29.4/moment.min.js', function() {
    if (!'zh-cn'.startsWith('en')) {
      Fluid.utils.createScript('https://lib.baomitu.com/moment.js/2.29.4/locale/zh-cn.min.js', function() {
        relativeDate();
      });
    } else {
      relativeDate();
    }
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
